#-*- coding: utf-8 -*-
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.loader import get_template
from django.template import RequestContext

from google.appengine.ext import db
from django.conf import settings
from models.main import App_user, Post, Comment, Tag

from smart_pager import Pager
from logics.main import get_user, set_user

from django.utils import simplejson
import re, datetime

def index(request, page = 1):
    page = int(page)
    if page < 1:
        page = 1
    page_size = 10
    total = Post.count()
    post_list = Post.get_list(page, page_size)

    pager = Pager(total, page_size, page, page_list_num = 8)

    return render_to_response('index.html', {
            'post_list': post_list,
            'pager': pager,
        }, RequestContext(request))

def show_post(request, post_key):
    post = db.get(post_key)
    #上一篇 和 下一篇
    pre_post = Post.all().order('offset').filter('offset > ', post.offset).get()
    next_post = Post.all().order('-offset').filter('offset < ', post.offset).get()

    return render_to_response('show_post.html', {
            'post': post,
            'pre_post': pre_post,
            'next_post': next_post,
            'user': get_user(),
            'comment_list': post.get_comment_list(),
        }, RequestContext(request))

def add_comment(request):
    post_key = request.POST['post_key'].strip()
    post = db.get(post_key)
    author = get_user()

    nickname = request.POST['nickname'].strip()
    email = request.POST['email'].strip()
    link = request.POST['link'].strip()
    if not link:
        link = None
    content = request.POST['content'].strip()

    if not nickname or not email or not content:
        return HttpResponse(simplejson.dumps({'state': 'err', 'msg': u'请完整填写昵称、电子邮件和内容'}))
    
    if not re.match(r'^\w+((_-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$', email):
        return HttpResponse(simplejson.dumps({'state': 'err', 'msg': u'邮箱地址格式不正确'}))

    ip = request.META["REMOTE_ADDR"]

    if author:
        Comment.auth_add(post, content, ip, author_nickname = nickname, link = link)
    else:
        Comment.anonymous_add(post, content, ip, email, nickname, link = link)
    
    return HttpResponse(simplejson.dumps({'state': 'ok', 'msg': u'评论发表成功'}))

def atom(request):
    post_list = Post.get_list(1, 10)

    return render_to_response('atom.xml', {
            'post_list': post_list,
            'blog_updated': datetime.datetime.utcnow(),
        }, RequestContext(request), mimetype = 'application/atom+xml')

def sitemap(request):
    post_list = Post.get_list(1, 200)

    return render_to_response('sitemap.xml', {
            'post_list': post_list,
            'blog_updated': datetime.datetime.utcnow(),
        }, RequestContext(request), mimetype="text/xml; charset=utf-8")